package cn.iocoder.yudao.module.game.controller.app;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.game.controller.admin.rechargerecord.vo.RechargeRecordSaveReqVO;
import cn.iocoder.yudao.module.game.controller.app.vo.HMOrder;
import cn.iocoder.yudao.module.game.controller.app.vo.HMOrderResult;
import cn.iocoder.yudao.module.game.controller.app.vo.RealPGResult;
import cn.iocoder.yudao.module.game.dal.dataobject.rechargerecord.RechargeRecordDO;
import cn.iocoder.yudao.module.game.service.rechargerecord.RechargeRecordService;
import cn.iocoder.yudao.module.game.utils.SHA256WithRSAUtils;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletTransactionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 用户收件地址")
@RestController
@RequestMapping("/game/p/hm")
@Validated
public class AppPayController {

    private String url = "https://pay.brazilpay.cc/api";

    private String mchid = "202403503";

    @Resource
    private RechargeRecordService rechargeRecordService;

    @Resource
    private PayWalletService payWalletService;

    @PostMapping("/createOrder")
    @Operation(summary = "创建用户收件地址")
    public CommonResult<Map<String, String>> pay(@RequestBody Map<String, Object> params) throws Exception {

        String action = "/pay";

        JSONObject data = new JSONObject();
        data.put("merId", mchid);
        data.put("orderId", params.get("sn").toString());
        data.put("orderAmt", params.get("amount").toString());
        data.put("channel", "PIX");
        data.put("desc", "rechargeOrder");
        data.put("userId", params.get("memberId").toString());
        data.put("ip", "54.233.242.50");
        data.put("notifyUrl", "https://api.dowin88.com/app-api/game/p/hm/notify");
        data.put("returnUrl", "https://g.dowin88.com/");
        data.put("nonceStr", UUID.randomUUID().toString().replace("-", "").substring(0, 32));
        data.put("sign", SHA256WithRSAUtils.generatorSign(data, 1));
        System.out.println("data: " + data.toString());
        // encrypt
        StringEntity entity = new StringEntity(data.toString());
        entity.setContentType("application/json");
        System.out.println(url + action);

        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url + action);
        httpPost.setEntity(entity);
        // gzip
        // httpPost.setHeader("Accept-Encoding", "gzip");
        HttpEntity httpEntity = null;
        String res = "{}";
        try {
            // Resolve response
            HttpResponse response = client.execute(httpPost);
            httpEntity = response.getEntity();
            res = EntityUtils.toString(httpEntity);
            System.out.println("POST:  " + res);
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            EntityUtils.consume(httpEntity);
        }
        return success(JSONObject.fromObject(res));
    }

    @PostMapping("/notify")
    @Operation(summary = "创建用户收件地址")
    public String notify(@RequestParam Map<String, Object> hmOrderResult) {
        System.out.println("pay:  " + hmOrderResult.get("merId"));
        RechargeRecordSaveReqVO updateReqVO = new RechargeRecordSaveReqVO();
        updateReqVO.setSn(hmOrderResult.get("orderId").toString());
        updateReqVO.setPaySn(hmOrderResult.get("sysOrderId").toString());
        updateReqVO.setStatus(hmOrderResult.get("status").toString());
        rechargeRecordService.updateRechargeRecordByOrderId(updateReqVO);

        RechargeRecordDO updateObj = rechargeRecordService.getRechargeRecordByOrderId(hmOrderResult.get("orderId").toString());
        PayWalletDO payWalletDO = payWalletService.getOrCreateWallet(updateObj.getMemberId(), UserTypeEnum.MEMBER.getValue());
        payWalletService.addWalletBalance(payWalletDO.getId(),
                hmOrderResult.get("orderId").toString(),
                PayWalletBizTypeEnum.RECHARGE,
                (updateObj.getAmount().multiply(new BigDecimal(100000)).longValue()));

        return "success";
    }

}
